<template>
  <div>
    <el-dialog width="70%" :visible.sync="formShow" @close="handleClickDeal('cancel')" v-dialog-drag :modal-append-to-body="false" :close-on-click-modal="false">
      <span slot="title">
        <i class="iconfont icon-ziliao"></i>
        <span>分包施工合同登记</span>
      </span>
      <div class="WholeScroll" style="max-height: 650px; overflow: auto">
        <el-form :model="formBaseData" ref="formBaseData" :rules="formBaseRules">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="基本信息" name="first">
              <el-row :span="24">
                <el-col :span="12">
                  <el-form-item label="项目" prop="project" :label-width="formlabelWidth">

                    <el-input v-model="formBaseData.project" placeholder="" disabled></el-input>

                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="标段" prop="sectionId" :label-width="formlabelWidth">

                    <el-input v-model="formBaseData.sectionId" placeholder="" disabled></el-input>

                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>

                <el-col :span="12">
                  <el-form-item label="标段号" :label-width="formlabelWidth" prop="subcontractCode">
                    <el-input v-model="formBaseData.subcontractCode" placeholder="" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="合同名称" prop="subcontractName" :label-width="formlabelWidth">
                    <el-input v-model="formBaseData.subcontractName" placeholder="" :disabled="detailType === 'check'"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-col :span="24">
                <el-form-item label="甲方单位参与人" prop="consMemberUidsJson" :label-width="formlabelWidth">
                  <el-select style="width: 100%" v-model="formBaseData.consMemberUidsJson" filterable placeholder="" :disabled="detailType === 'check'" multiple>
                    <el-option v-for="(item, i) in selectList.firstPartUserOpts" :key="i" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-row :span="24">
                <el-col :span="24">
                  <el-form-item label="分包单位" :label-width="formlabelWidth">
                    <el-select style="width: 100%" v-model="formBaseData.subcontractCompany" @change="getSecondPartUserTree(clearSubcontractUsersList)" :disabled="detailType === 'check'" filterable placeholder="">
                      <el-option v-for="(item, i) in selectList.companyListFiltered" :key="i" :label="item.fullname" :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :span="24">
                <el-col :span="24">
                  <el-form-item label="分包单位参与人" :label-width="formlabelWidth">
                    <cmsPopoverTree :defaultProps="defaultProps" ref="cmsPopoverTree" :data="linkUserOpts" :selectVal="checkedLinkUsers" type="multi" @addMulTag="addMulTag" :defaultIds="defaultIds" @delTag="delTag" @addTag="addTag" :disabled="detailType === 'check'" />
                  </el-form-item>

                </el-col>
              </el-row>
              <el-row :span="24">
                <el-col :span="12">
                  <el-form-item label="合同总金额" :label-width="formlabelWidth" prop="subcontractPrice">
                    <el-input v-model="formBaseData.subcontractPrice" oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="" :disabled="detailType === 'check'">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="安全生产费合同金额" :label-width="formlabelWidth">
                    <el-input v-model="formBaseData.safetyMoney" oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="" :disabled="detailType === 'check'">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>

              </el-row>
              <el-row :span="24">
                <el-col :span="12">
                  <el-form-item label="环保合同金额" :label-width="formlabelWidth">
                    <el-input v-model="formBaseData.environmentalMoney" oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="" :disabled="detailType === 'check'">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="暂列金合同金额" :label-width="formlabelWidth">
                    <el-input style="width: 100%" v-model="formBaseData.provisionalSum" oninput="value=value.replace(/[^-\d.]/g,'')" placeholder="" :disabled="detailType === 'check'">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="变更增减暂列金" :label-width="formlabelWidth">
                    <el-input style="width: 100%" v-model="formBaseData.modifyProvisionalSum " oninput="value=value.replace(/[^-\d.]/g,'')" placeholder="" :disabled="detailType === 'check'">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="'发包人提供的创优基金\n合同金额'" class="foldLabel" :label-width="formlabelWidth">
                    <el-input style="width: 100%" v-model="formBaseData.employerChuangyouFundMoney" oninput="value=value.replace(/[^-\d.]/g,'')" placeholder="" :disabled="detailType === 'check'">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="计日工项目合同金额" :label-width="formlabelWidth">
                    <el-input style="width: 100%" v-model="formBaseData.dayworkProjectsContract " oninput="value=value.replace(/[^-\d.]/g,'')" placeholder="" :disabled="detailType === 'check'">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="存量工程" :label-width="formlabelWidth">
                    <el-input style="width: 100%" v-model="formBaseData.stockEngineering" oninput="value=value.replace(/[^-\d.]/g,'')" placeholder="" :disabled="detailType === 'check'">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="扣除承包人创优基金" prop="deductContractorChuangyouFund" :label-width="formlabelWidth">
                    <el-input style="width: 100%" v-model="formBaseData.deductContractorChuangyouFund" placeholder="" type="number" :disabled="detailType === 'check'">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="扣除发包人创优基金" prop="deductEmployerChuangyouFund" :label-width="formlabelWidth">
                    <el-input style="width: 100%" v-model="formBaseData.deductEmployerChuangyouFund" placeholder="" :disabled="detailType === 'check'">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="扣除保证金总百分比" prop="deductMarginPercentage" :label-width="formlabelWidth">
                    <el-input style="width: 100%" v-model="formBaseData.deductMarginPercentage " @blur="otherMarginCalculate" placeholder="" :disabled="detailType === 'check'">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="扣除农民工工资保证金" :label-width="formlabelWidth" prop="deductMigrantWorkerMargin">
                    <el-input style="width: 100%" v-model="formBaseData.deductMigrantWorkerMargin" placeholder="" @blur="otherMarginCalculate" :disabled="detailType === 'check'">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="扣除质量保证金" :label-width="formlabelWidth" prop="deductQualityMargin">
                    <el-input style="width: 100%" v-model="formBaseData.deductQualityMargin " placeholder="" @blur="otherMarginCalculate" :disabled="detailType === 'check'">
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <!-- <el-col :span="12">
                  <el-form-item label="其他保证金" :label-width="formlabelWidth">
                    <el-input style="width: 100%" v-model="formBaseData.otherMargin" placeholder="" disabled>
                      <template slot="append">%</template>
                    </el-input>
                  </el-form-item>
                </el-col> -->
                <el-col :span="12">
                  <el-form-item label="扣除质量保证金限额" :label-width="formlabelWidth">
                    <el-input style="width: 100%" v-model="formBaseData.deductQualityMarginLimit " oninput="value=value.replace(/[^-\d.]/g,'')" placeholder="" :disabled="detailType === 'check'">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="19" style="position: relative">
                  <el-form-item label="附件" :label-width="formlabelWidth" class="upload-demo fill span18">
                    <cmsUploadFile ref="fileOne" :detail-id="detailFileId" :fileList="fileList" :fileSystem="fileSystem['one']" :disabled="detailType === 'check'|| detailType === 'audit'" type="mul" info="支持上传 png/jpg/gif/doc/xlsx/ppt/pdf 文件" :detail-type="detailType" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <!--新建和编辑的暂存上报-->
        <template v-if="detailType === 'error' || detailType === 'edit'">
          <el-button size="small" type="primary" @click="handleClickDeal('submit', {flag: 1})" :loading="isLoading"><i class="iconfont icon-icon_save"></i> 确 定
          </el-button>
        </template>
        <el-button size="small" @click="handleClickDeal('cancel')"><i class="iconfont icon-icon_cancel"></i> 取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import cmsPopoverTree from '@/views/components/cmsPopoverTree.vue'
import crudSection from '@/api/buss/sectionInfo'
import msgUtil from '@/utils/msgUtil'
import crudProject from '@/api/buss/project'
import dept from '@/api/system/dept'
import subcontract from '@/api/buss/subcontractRegistration'
import { getSecondPartUserTree } from "../../../../api/buss/project";

export default {
  name: 'contract-registration-detail',
  components: {
    cmsPopoverTree,

  },
  props: {
    postDetail: {
      type: Object,
      default: {
        show: false,
        type: 'build',
        params: {}
      }
    }
  },
  watch: {
    postDetail(value) {
      // 显示详情弹窗
      this.formShow = value.show
      // 初始化窗口参数
      this.activeName = 'first'
      // 详情类型
      this.detailType = value.type
      this.parentProjectId = value.params.projectId
      this.parentSetionId = value.params.setionId
      //this.setionCode = value.params.setionCode

      if (value.params.subContractId) {
        this.subContractId = value.params.subContractId
        this.detailId = value.params.subContractId
      }
      this.detailId = value.params.id ? value.params.id : '';

      this.initData()

      if (this.detailType == 'check' || this.detailType == 'edit') {
        // 获取详情请求
        this.getDetail()
      }

    }
  },
  data() {
    return {
      linkUsers: {},
      ownerRepresentativeUsers: {},
      ownerRepresentativeUserOpts: [],
      linkUserOpts: [],
      checkedLinkUsers: [],
      defaultIds: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },

      subContractId: '',
      setionCode: '',
      parentProjectId: '',
      parentSetionId: '',
      alreadyUploadFiles: [],
      // actionType: '查看',
      // title: '人员',
      //存放图片的数组
      fileListArray: [],
      detailType: 'build', // 详情类型 build新建 check不可编辑查看 edit编辑
      detailId: '', // 当前详情的id
      detailFileId: '', // 获取文件form的id
      activeName: 'first', //
      detailActions: [], // 当前详情的操作项
      formShow: false, // 表单展示
      radioValue: '',//单选按钮选中的值
      formlabelWidth: '180px', // 表单左侧标题宽度
      formlabelWidth2: '120px', // 表单左侧标题宽度
      selectList: {
        stationType: [],//岗位
        credentialsType: [],//资格证书
        file: [], // 文件
        approver: [], // 审批人
        structureType: [], // 结构类型
        workContractList: [],
        companyListFiltered: [],
        secondPartUserOpts: [],
        //  甲方标段管理人选择项
        firstPartUserOpts: [],
      },
      fileList: [],
      fileSystem: {
        'one': {
          sys: 'buss',
          module: 'subcontractRegistration',
          part: 'one',
          compoName: 'fileOne'
        }
      },

      /* fileSystem: {
           attachId: '',
           sys: 'buss',
           viewByAnon: true,
           longLife: false,
           module: 'subcontractRegistration',
           part: ['one'],
       }, // 文件系统的参数*/
      // 所有下拉框列表的集合
      formBaseData: {
        safetyMoney: '',
        subcontractUsersList: [],
        contract: { id: '' },
        subcontractCode: '',
        subcontractName: '',
        subcontractPrice: '',
        subcontractCompany: '',
        subcontractUsers: '',
        subcontractCompanyDirector: '',
        subcontractSigningTime: '',
        rate: '',
        startPileNumber: '',
        endPileNumber: '',
        congtractLong: '',
        subcontractDay: '',
        contractType: '工程类合同-施工',
        project: '',
        projectId: '',
        sectionId: '',
        allListMoney: '',
        engineeringPremium: '',
        managementCost: '',
        areamoney: '',
        designExpense: '',
        employerChuangyouFundMoney: '',
        dayworkProjectsContract: '',
        stockEngineering: '',
        deductContractorChuangyouFund: '',
        deductEmployerChuangyouFund: '',
        deductMarginPercentage: '',
        deductMigrantWorkerMargin: '',
        deductQualityMargin: '',
        otherMargin: '',
        deductQualityMarginLimit: '',
        environmentalMoney: '',
        consMemberUidsJson: [],
      }, // 表单基本信息内容
      formBaseRules: {
        project: [
          { required: true, message: '请选择' + '项目', trigger: 'blur' },
        ],
        sectionId: [
          { required: true, message: '请选择' + '标段', trigger: 'blur' },
        ],
        subcontractCode: [
          { required: true, message: '请输入' + '合同编号', trigger: 'blur' },
        ],
        subcontractName: [
          { required: true, message: '选择' + '合同名称', trigger: 'blur' },
        ],
        subcontractPrice: [
          { required: true, message: '请输入' + '合同总金额', trigger: 'blur' },
        ],
        subcontractCompany: [
          { required: true, message: '请选择' + '分包单位名称', trigger: 'blur' },
        ],
        deductQualityMargin: [
          { required: false, message: '请输入' + ' ', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback()
              }
              if (!this.validateNumber(value)) {
                return callback(new Error('请输入0-100的自然数,最多两位小数'))
              } else {
                return callback()
              }
            },
            trigger: 'blur',
          },
        ],
        deductMigrantWorkerMargin: [
          { required: false, message: '请输入' + ' ', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback()
              }
              if (!this.validateNumber(value)) {
                return callback(new Error('请输入0-100的自然数,最多两位小数'))
              } else {
                return callback()
              }
            },
            trigger: 'blur',
          },
        ],
        otherMargin: [
          { required: false, message: '请输入' + ' ', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback()
              }
              if (!this.validateNumber(value)) {
                return callback(new Error('请输入0-100的自然数,最多两位小数'))
              } else {
                return callback()
              }
            },
            trigger: 'blur',
          },
        ],
        deductMarginPercentage: [
          { required: false, message: '请输入' + ' ', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback()
              }
              if (!this.validateNumber(value)) {
                return callback(new Error('请输入0-100的自然数,最多两位小数'))
              } else {
                return callback()
              }
            },
            trigger: 'blur',
          },
        ],
        deductEmployerChuangyouFund: [
          { required: false, message: '请输入' + ' ', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback()
              }
              if (!this.validateNumber(value)) {
                return callback(new Error('请输入0-100的自然数,最多两位小数'))
              } else {
                return callback()
              }
            },
            trigger: 'blur',
          },
        ],
        deductContractorChuangyouFund: [
          { required: false, message: '请输入' + ' ', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback()
              }
              if (!this.validateNumber(value)) {
                return callback(new Error('请输入0-100的自然数,最多两位小数'))
              } else {
                return callback()
              }
            },
            trigger: 'blur',
          },
        ],
        /*   subcontractUsersList: [
               {required: true, message: '请输入' + '分包单位参与人', trigger: 'blur'},
           ],*/
        subcontractCompanyDirector: [
          { required: true, message: '请输入' + '分包合同负责人（乙方）', trigger: 'blur' },
        ],
        subcontractSigningTime: [
          { required: true, message: '请输入' + '合同签订日期', trigger: 'blur' },
        ],
        fujian1: [
          { required: true, message: '请选择' + '附件', trigger: 'blur' },
        ],
        fujian2: [
          { required: true, message: '请选择' + '附件', trigger: 'blur' },
        ],
        consMemberUidsJson: [
          {
            required: false,
            message: '请选择' + '甲方单位参与人',
            trigger: 'change'
          }
        ],
      }, // 表单基本信息验证
      projectTree: [],
      sectionId: "",
      sectionSelectionTree: [],
      isLoading: false, // 提交按钮loading
    }
  },
  created() {

  },
  methods: {
    limitNumber(val) {
      console.log('xxxxxxx', val)
      const regex = /^(?:100|[1-9]?\d|\d)$/;
      if (!regex.test(val)) {
        // 如果输入值不在0到100之间，清空输入框的值
        val = '';
      }
    },
    otherMarginCalculate() {
      let data1 = this.formBaseData.deductMarginPercentage
      let data2 = this.formBaseData.deductMigrantWorkerMargin
      let data3 = this.formBaseData.deductQualityMargin
      data1 = data1 >= 0 && data1 <= 100 ? data1 : 0
      data2 = data2 >= 0 && data2 <= 100 ? data2 : 0
      data3 = data3 >= 0 && data3 <= 100 ? data3 : 0
      this.formBaseData.otherMargin = Number(data1) - Number(data2) - Number(data3)
      this.$forceUpdate()
    },
    validateNumber(str) {
      return new RegExp('(^(\\d|[1-9]\\d)(\\.\\d{1,2})?$)|(^100$)').test(str)
    },
    getLinkUserOpts(compId) {


      this.linkUserOpts = []
      this.checkedLinkUsers = []

      crudProject.getlinkUsersDept(compId).then(res => {
        if (res.status === 1) {
          let linkUserOpts = res.data;
          this.linkUserOpts = linkUserOpts;
          let ownerRepresentativeUserOpts = res.data;
          this.ownerRepresentativeUserOpts = ownerRepresentativeUserOpts;
          console.log(res.data, '俏丽吗++++++++++++++++++++++++++')
          this.collectDeptUserById(linkUserOpts);
          this.collectDeptUserCompById(ownerRepresentativeUserOpts);
          this.$forceUpdate();
        } else {
          //this.$messageError(res.data.message)
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取部门用户列表失败!')
      })
    },


    getLinkUserOptss(compId) {
      return crudProject.getlinkUsersDept(compId).then(res => {
        if (res.status === 1) {
          let linkUserOpts = res.data;
          //if(this.detailType != 'edit'){
          this.linkUserOpts = linkUserOpts;
          //}
          let ownerRepresentativeUserOpts = res.data;
          this.ownerRepresentativeUserOpts = ownerRepresentativeUserOpts;
          console.log(res.data, '俏丽吗++++++++++++++++++++++++++')
          this.collectDeptUserById(linkUserOpts);
          this.collectDeptUserCompById(ownerRepresentativeUserOpts);
          return new Promise(reslove => {
            reslove(res)
          })
          this.$forceUpdate();
        } else {
          //this.$messageError(res.data.message)
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取部门用户列表失败!')
      })
    },


    collectDeptUserById(linkUserOpts) {
      for (let i = 0; i < linkUserOpts.length; i++) {
        let user = linkUserOpts[i]
        let id = user.id
        let children = user.children
        this.linkUsers[id] = user
        if (children && children.length > 0) {
          this.collectDeptUserById(children)
        }
      }
    },

    collectDeptUserCompById(ownerRepresentativeUserOpts) {
      for (let i = 0; i < ownerRepresentativeUserOpts.length; i++) {
        let user = ownerRepresentativeUserOpts[i]
        let id = user.id
        let children = user.children

        this.ownerRepresentativeUsers[id] = user
        if (children && children.length > 0) {
          this.collectDeptUserCompById(children)
        }
      }
    },

    /**
     *  -----@addMulTag="addMulTag"
     * 多选增加--多选模式使用
     * @param val
     */
    addMulTag(val) {
      console.log(val)
      // this.checkedLinkUsers.splice(0, this.checkedLinkUsers.length)
      this.checkedLinkUsers = []
      val.forEach((item) => {
        this.checkedLinkUsers.push(item)
      })
      this.$forceUpdate()
    },
    /**
     * 删除会签部门人
     */
    delTag(val) {
      this.checkedLinkUsers.splice(val, 1)

      this.$forceUpdate()
      this.$refs.cmsPopoverTree.updateTree()
      this.$refs.cmsPopoverTree.$forceUpdate()
    },
    /**
     * 增加会签人
     * @param val
     */
    addTag(val) {
      this.checkedLinkUsers.push(val)
      this.$refs.cmsPopoverTree.updateTree()
      this.$refs.cmsPopoverTree.$forceUpdate()
      this.$forceUpdate()
    },





    initData() {
      crudProject.getOne(this.parentProjectId).then(res => {
        if (res.status == 1) {
          let formBaseData = res.data;
          this.formBaseData.projectId = formBaseData.id
          this.formBaseData.project = formBaseData.proName

        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取详情信息失败")
      })

      crudSection.getOne(this.parentSetionId).then(res => {
        if (res.status == 1) {
          let formBaseData = res.data;
          this.formBaseData.sectionId = formBaseData.name
          this.formBaseData.sectionInfoId = formBaseData.id
          this.formBaseData.subcontractCode = formBaseData.code

        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取详情信息失败")
      })


      crudProject.getFirstPartUserTree(this.parentProjectId).then(res => {
        if (res.status == 1) {
          if (res.data) {
            this.selectList.firstPartUserOpts = res.data
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取详情信息失败")
      })


      dept.listForSys("").then(res => {
        this.selectList.companyList = []
        if (res.code === 200) {
          res.data.forEach((item) => {
            this.$set(
              this.selectList.companyList,
              this.selectList.companyList.length,
              item
            )
          })
          this.selectList.companyListFiltered = this.selectList.companyList.filter(cp => cp.typeName && cp.typeName.indexOf("施工单位") >= 0);
        } else {
          msgUtil.error2(res.data.message)
        }
      })
    },



    /**
     * 清空参与人
     *
     * */
    clearSubcontractUsersList() {
      this.formBaseData.subcontractUsersList = [];
      this.checkedLinkUsers = []
    },

    /**
     * 获取乙方单位参与人
     * */
    getSecondPartUserTree() {

      this.getLinkUserOpts(this.formBaseData.subcontractCompany)
      /*  this.formBaseData.subcontractUsersList = []
       return  crudProject.getSecondPartUserTree(this.formBaseData.subcontractCompany).then(res => {
          if (res.status == 1) {

            if(res.data){
              this.selectList.secondPartUserOpts = res.data
            }
            this.formBaseData.memberUids = []

            return new Promise(reslove=>{
              reslove(res)
            })

          }else {
            msgUtil.error2(res.data.message)
          }
        }).catch(() => {
          msgUtil.error2("获取详情信息失败")
        })*/
    },

    refresh() {
      this.$forceUpdate()
    },

    // 获取详情请求 api
    getDetail() {
      subcontract.getOne(this.subContractId).then(res => {
        if (res.status == 1) {

          let formBaseData = res.data;

          let data = res.data
          this.formBaseData = data

          this.formBaseData.id = data.id
          this.detailFileId = data.id

          this.formBaseData.projectId = data.project.id
          this.formBaseData.project = data.project.proName
          this.formBaseData.sectionId = data.sectionInfo.name
          this.formBaseData.sectionInfoId = data.sectionInfo.id
          this.formBaseData.subcontractCode = data.sectionInfo.code

          this.formBaseData.subcontractCompany = data.subcontractCompany
          /* this.getSecondPartUserTree().then(res=>{
           })*/

          let linkUsers = formBaseData.subcontractUsers
          this.formBaseData.subcontractUsers = linkUsers

          this.getLinkUserOptss(data.subcontractCompany).then(res => {
            if (linkUsers) {
              let linkUserIds = formBaseData.subcontractUsers.split(',')
              let checkedLinkUsers = []
              for (let i = 0; i < linkUserIds.length; i++) {
                let linkUser = this.linkUsers[linkUserIds[i]]
                if (linkUser) {
                  checkedLinkUsers.push(linkUser)

                }
              }
              this.$set(this, 'checkedLinkUsers', checkedLinkUsers)
              //this.checkedLinkUsers = checkedLinkUsers
            } else {
              this.$set(this, 'checkedLinkUsers', [])
              //this.checkedLinkUsers = []
            }
          })


          //this.formBaseData.subcontractUsersList = eval("(" + data.subcontractUsers + ")")

          this.loadFiles()
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取详情信息失败111111111111")
      })

    },
    // 提交详情 提交1/暂存0 新建0/修改1
    submitDetail(type, callback) {
      console.log(this.detailType)

      let linkUserIds = []
      let checkedLinkUsers = this.checkedLinkUsers
      // if(checkedLinkUsers.length<=0){
      //   this.isLoading = false
      //   msgUtil.error2("请选择【分包分包单位参与人】！")
      //   return
      // }
      for (let i = 0; i < checkedLinkUsers.length; i++) {
        linkUserIds.push(checkedLinkUsers[i].id)
      }
      this.formBaseData.subcontractUsersList = linkUserIds
      this.formBaseData.subcontractUsers = linkUserIds.join(',')
      if (this.detailType === 'error') {
        subcontract.submit(this.formBaseData).then(res => {
          if (res.status === 1) {
            this.detailId = res.data.id
            this.saveFiles()
            //this.isLoading = false
            this.$notify({
              title: '数据修改成功',
              type: 'success',
              duration: 1500
            })
            // 传值给父组件刷新列表
            this.$emit('reloadList')
            this.formShow = false

          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch((response) => {
          this.$notify({
            title: '数据表新增失败',
            type: 'error',
            duration: 2500
          })
        }).finally((response) => {
          this.isLoading = false
        })
      } else {
        subcontract.resubmit(this.formBaseData).then(res => {
          if (res.status === 1) {
            this.detailId = res.data.id
            this.saveFiles()
            //this.isLoading = false
            this.$notify({
              title: '数据修改成功',
              type: 'success',
              duration: 1500
            })
            // 传值给父组件刷新列表
            this.$emit('reloadList')
            this.formShow = false

          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch((response) => {
          this.$notify({
            title: '数据表新增失败',
            type: 'error',
            duration: 2500
          })
        }).finally((response) => {
          this.isLoading = false
        })
      }

    },
    // 事件处理的api请求
    sealDealHttp(url, query, params, callback) {
      this.$httpPost(
        this.$store.state.httpHost.buss + url + query,
        params
      ).then(res => {
        if (res.data.status === 1) {
          if (callback) callback(res.data)
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        console.log(res)
      })
    },
    // 点击各个流程的按钮事件
    handleClickDeal(type, res) {
      console.log(type, res)
      switch (type) {
        // 取消，关闭窗口
        case 'cancel':
          // 重置表单验证
          this.$refs['formBaseData'].resetFields()
          // 清空表单内容
          this.formBaseData = {
            safetyMoney: '',
            environmentalMoney: '',
            subcontractUsersList: [],
            contract: { id: '' },
            subcontractCode: '',
            subcontractName: '',
            subcontractPrice: '',
            subcontractCompany: '',
            subcontractUsers: '',
            subcontractCompanyDirector: '',
            subcontractSigningTime: '',
            rate: '',
            startPileNumber: '',
            endPileNumber: '',
            congtractLong: '',
            subcontractDay: '',
            contractType: '工程类合同-施工',
            project: '',
            projectId: '',
            sectionId: '',
            allListMoney: '',
            engineeringPremium: '',
            managementCost: '',
            areamoney: '',
            designExpense: '',
            employerChuangyouFundMoney: '',
            dayworkProjectsContract: '',
            stockEngineering: '',
            deductContractorChuangyouFund: '',
            deductEmployerChuangyouFund: '',
            deductMarginPercentage: '',
            deductMigrantWorkerMargin: '',
            deductQualityMargin: '',
            otherMargin: '',
            deductQualityMarginLimit: '',
            consMemberUidsJson: []
          } // 表单基本信息内容
          this.fileList = []


          this.linkUsers = {}
          this.ownerRepresentativeUsers = {}
          this.ownerRepresentativeUserOpts = []
          this.linkUserOpts = []
          this.checkedLinkUsers = []
          this.defaultIds = []

          for (let k in this.fileSystem) {
            let fileProp = this.fileSystem[k]
            this.$refs[fileProp.compoName].cancelAll()
          }
          this.setionCode = ''
          this.parentProjectId = '',
            this.parentSetionId = '',
            this.linkName = ''
          this.radioValue = ''
          // 清空文件
          this.selectList.file = []
          // 关闭弹窗
          this.formShow = false
          //清空按钮 数组
          this.fileListArray = []
          //清空已上传文件的数组
          this.alreadyUploadFiles = []
          break
        // 保存
        case 'submit':
          let flag = res.flag
          // 表单验证
          this.$refs['formBaseData'].validate((valid) => {
            if (valid) {
              this.isLoading = true
              // 提交详情
              this.submitDetail(flag, () => {
              })
            } else {
            }
          })
          break
      }
    },



    saveFiles() {
      for (let k in this.fileSystem) {
        let fileProp = this.fileSystem[k]
        this.$refs[fileProp.compoName].saveAll(this.detailId)
      }
    },

    loadFiles() {
      this.$nextTick(() => {
        for (let k in this.fileSystem) {
          let fileProp = this.fileSystem[k]
          this.$refs[fileProp.compoName].init()
        }
      })
    },

    handleClick() {
    },
  },

  filters: {
    numFilter(value) {
      try {
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [], counter = 0;
        num = (num || 0).toString().split('');
        for (let i = num.length - 1; i >= 0; i--) {
          counter++;
          result.unshift(num[i]);
          if (!(counter % 3) && i != 0) {
            result.unshift(',');
          }
        }
        let after = numSmall === undefined ? result.join('') : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        return ""
      }
    },
    numFilter2(value) {
      try {
        let before = value.toFixed(2)
        return before
      } catch (e) {
        return ""
      }
    }
  },
}
</script>

<style scoped lang="scss">
.fee_add {
  color: #008fe0;
  border-color: #008fe0;
  float: right;
  margin-bottom: 10px;
}

.el-input__inner {
  width: 291px;
}

.dialogTableDiv {
  width: 100%;
  margin: 0 auto;

  .tableTitle {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;

    p {
      font-size: 16px;
    }

    .add {
      background-color: #ffffff;
      color: rgb(73, 163, 250);
    }
  }
}

.meterage-manage-detail
  .el-date-editor.el-input.el-input--prefix.el-input--suffix.el-date-editor--date {
  width: 255px;
}

/*.tree-menu {*/
/*color: black !important;*/
/*div{*/
/*color: black !important;*/
/*}*/
/*}*/
::v-deep.el-form-item.foldLabel .el-form-item__label {
  white-space: pre-line; /*换行显示*/
  height: 32px; /*设置lable高度，与input高度一样*/
  line-height: 20px !important; /*设置行高为label高度的一半（有n行就是label高度的1/n）*/
}
</style>
<style lang="scss">
.el-message-box {
  .el-message-box__btns {
    .el-button {
      font-size: 14px;
    }
  }
}
</style>
